/* eslint-disable camelcase */
/**
 * 加密工具类方法
 * @author linjianqun
 * @version 2018-04-21
 */
/* eslint-disable no-unused-vars */
let CryptoJS = require("crypto-js");
let GM = require('./GM.js');

const SM4_IV = '06060606060606060808080808080808';
const SM4_KEY = '65637321402324255e262a282971617a';

function sm4Decrypt(content) {
  if (!SM4_KEY || !content) {
    return content;
  }
  let sm4 = new GM.SM4();
  let inputBytes = GM.Hex.decode(content);
  let key = GM.Hex.decode(SM4_KEY);
  // ecb解密
  // let plain = sm4.decrypt_ecb(key, inputBytes); 

  // cbc解密，比ecb多了iv
  let iv = GM.Hex.decode(SM4_IV);
  let plain = sm4.decrypt_cbc(key, iv, inputBytes); 

  let result = GM.Hex.bytesToUtf8Str(plain)
  return result;
}

function _processKey(srcKey) {
  const keyLen = 8;
  const srcKeyLen = srcKey.length;
  if (srcKeyLen > keyLen) {
    srcKey = srcKey.substr(0, keyLen);
  } else {
    const paddLen = keyLen - srcKeyLen;
    for (let i = 0; i < paddLen; i += 1) {
      srcKey += '0';
    }
  }
  return CryptoJS.enc.Utf8.parse(srcKey);
}

/**
 * 加密方法
 * @param { String } content
 * @param { String } srcKey
 */
function encrypt(content, srcKey) {
  if (!srcKey) {
    return '';
  }
  const key = _processKey(srcKey);
  const encryptStr = CryptoJS.DES.encrypt(content, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encryptStr.toString();
}

/**
 * 解密
 * @param {*} content
 * @param {*} srcKey
 */
function decrypt(content, srcKey) {
  if (!srcKey) {
    return '';
  }
  const key = _processKey(srcKey);
  const ciphertext = CryptoJS.enc.Base64.parse(content);
  let decryptStr = CryptoJS.DES.decrypt({
    ciphertext
  }, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  decryptStr = decryptStr.toString();
  const result = [];
  for (let index = 0; index < decryptStr.length; index += 2) {
    const char = decryptStr[index] + decryptStr[index + 1];
    result.push(String.fromCharCode(parseInt(char, 16)));
  }
  return result.join('');
}

function RSAEncrypt(value, srcKey) {
  if (!isSecurity) {
    return encrypt(value, srcKey);
  }
  const pk = {
    n: '55ad4b6c739452c01710d7763455abca358fc472a243517e743ef1d69618b6396fe7a76409cef96b716cb73723235f56614e19ee16bd0e0a8f47b8639ef15b6a95124e984757133060114472ef20ff18087cef05647d02ed70c3e7a9afb1ed0023cedcf64f9eea0d8ae0be7d68938f5c413077978d5435621f2c52524dbf8a97',
    e: '10101'
  };
  const rsa = new RSAKey();
  rsa.setPublic(pk.n, pk.e);
  return rsa.encrypt(value);
}

function MD5Encrypt(value) {
  return hex_md5(value);
}

module.exports = {
  encrypt,
  decrypt,
  sm4Decrypt,
  RSAEncrypt,
  MD5Encrypt
};
